<template>
	<view class="page">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title elderly-text-large">💊 药品识别</text>
			<text class="page-subtitle elderly-text">拍照识别药品信息，智能播报用法用量</text>
		</view>
		
		<!-- 拍照识别区域 -->
		<view class="capture-section">
			<view class="capture elderly-pressable" :class="{ disabled: isLoading }" @tap="scan">
				<view class="capture-icon">
					<text class="camera-emoji">📷</text>
				</view>
				<text class="capture-text elderly-text-large">{{isLoading ? '识别中...' : '点击拍照识别'}}</text>
				<text class="capture-hint elderly-text">将药品包装盒对准摄像头</text>
			</view>
			
			<!-- 加载状态 -->
			<view class="loading-overlay" v-if="isLoading">
				<view class="loading-spinner">
					<text class="spinner-icon">⏳</text>
				</view>
				<text class="loading-text elderly-text">正在识别药品信息，请稍候...</text>
				<view class="loading-progress">
					<view class="progress-bar" :style="{width: loadingProgress + '%'}"></view>
				</view>
			</view>
		</view>
		
		<!-- 识别结果 -->
		<view class="result-section" v-if="content">
			<view class="result-header">
				<text class="result-title elderly-text-large">📋 识别结果</text>
				<view class="result-actions">
					<view class="action-btn elderly-pressable" @tap="copyResult">
						<text class="action-icon">📋</text>
						<text class="action-label elderly-text">复制</text>
					</view>
					<view class="action-btn elderly-pressable" @tap="shareResult">
						<text class="action-icon">📤</text>
						<text class="action-label elderly-text">分享</text>
					</view>
				</view>
			</view>
			
			<view class="result-content">
				<text class="result-text elderly-text">{{content}}</text>
			</view>
			
			<!-- 结构化信息 -->
			<view class="structured-info" v-if="structuredData">
				<view class="info-item" v-if="structuredData.usage">
					<text class="info-label elderly-text">用法用量：</text>
					<text class="info-value elderly-text">{{structuredData.usage}}</text>
				</view>
				<view class="info-item" v-if="structuredData.caution">
					<text class="info-label elderly-text">注意事项：</text>
					<text class="info-value elderly-text">{{structuredData.caution}}</text>
				</view>
				<view class="info-item" v-if="structuredData.contraindication">
					<text class="info-label elderly-text">禁忌症：</text>
					<text class="info-value elderly-text">{{structuredData.contraindication}}</text>
				</view>
			</view>
		</view>
		
		<!-- 语音播报控制 -->
		<view class="voice-controls" v-if="content">
			<view class="voice-btn elderly-pressable" :class="{ active: isSpeaking }" @tap="speak">
				<text class="voice-icon">{{isSpeaking ? '🔊' : '🔇'}}</text>
				<text class="voice-label elderly-text">{{isSpeaking ? '正在播报' : '语音播报'}}</text>
			</view>
			<view class="voice-settings elderly-pressable" @tap="openSpeakSettings">
				<text class="settings-icon">⚙️</text>
			</view>
		</view>
		
		<!-- 手动输入 -->
		<view class="manual-input">
			<text class="input-title elderly-text">手动输入药品名称</text>
			<input 
				class="manual-input-field elderly-text" 
				v-model="manual" 
				placeholder="若拍照识别不便，可手动输入药品名称" 
				placeholder-class="ph"
				@confirm="handleManualInput"
			/>
			<view class="input-actions">
				<button class="input-btn elderly-pressable" @tap="handleManualInput">确认输入</button>
				<button class="input-btn elderly-pressable" @tap="clearManual">清空</button>
			</view>
		</view>
		
		<!-- 功能操作 -->
		<view class="function-actions" v-if="content">
			<view class="func-btn elderly-pressable" @tap="openManual">
				<text class="func-icon">📖</text>
				<text class="func-label elderly-text">药品说明书</text>
			</view>
			<view class="func-btn elderly-pressable" @tap="openCaution">
				<text class="func-icon">⚠️</text>
				<text class="func-label elderly-text">用药注意事项</text>
			</view>
			<view class="func-btn elderly-pressable" @tap="addReminder">
				<text class="func-icon">⏰</text>
				<text class="func-label elderly-text">添加用药提醒</text>
			</view>
		</view>
		
		<!-- 历史记录 -->
		<view class="history-section" v-if="history.length">
			<view class="history-header">
				<text class="history-title elderly-text-large">📚 历史记录</text>
				<view class="history-clear elderly-pressable" @tap="clearHistory">
					<text class="clear-icon">🗑️</text>
				</view>
			</view>
			<view class="history-list">
				<view class="history-item elderly-pressable" v-for="(h,i) in history" :key="i" @tap="applyHistory(h)">
					<view class="history-content">
						<text class="history-name elderly-text">{{h.name}}</text>
						<text class="history-time elderly-text">{{formatTime(h.time)}}</text>
					</view>
					<text class="history-arrow">›</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default{
    data(){
        return{
            content:'', 
            manual:'', 
            isLoading:false, 
            history:[], 
            voiceRate:1, 
            voiceType:'female',
            isSpeaking: false,
            loadingProgress: 0,
            structuredData: null,
            // 药品识别相关
            drugDatabase: [
                {
                    name: '阿司匹林',
                    usage: '每日1-2次，每次1片，饭后服用',
                    caution: '胃溃疡患者慎用，避免空腹服用',
                    contraindication: '对本品过敏者禁用'
                },
                {
                    name: '降压药',
                    usage: '每日1次，每次1片，早晨服用',
                    caution: '定期监测血压，不可随意停药',
                    contraindication: '严重肝肾功能不全者禁用'
                }
            ]
        }
    },
    computed:{
        canSpeak(){ return !!this.content && !this.isLoading }
    },
    onLoad(){ this.loadHistory() },
    methods:{
        scan(){
            if(this.isLoading) return
            
            // 触觉反馈
            if (uni.vibrateShort) {
                try { uni.vibrateShort({ type: 'medium' }) } catch(e){}
            }
            
            this.isLoading = true
            this.loadingProgress = 0
            
            // 模拟加载进度
            const progressInterval = setInterval(() => {
                this.loadingProgress += 10
                if (this.loadingProgress >= 100) {
                    clearInterval(progressInterval)
                }
            }, 120)
            
            // 真实项目请接入 OCR；这里用相机占位，并生成示例文本
            uni.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['camera', 'album'],
                success: (res) => {
                    setTimeout(() => {
                        // 模拟OCR识别结果
                        this.content = '用法用量：每日2次，每次1片；禁忌：对本品过敏者禁用。'
                        this.structuredData = {
                            usage: '每日2次，每次1片',
                            caution: '饭后服用，避免空腹',
                            contraindication: '对本品过敏者禁用'
                        }
                        this.pushHistory({ 
                            name: '示例药品', 
                            content: this.content, 
                            time: Date.now(),
                            structured: this.structuredData
                        })
                        this.isLoading = false
                        this.loadingProgress = 100
                        
                        // 自动播报识别结果
                        this.speak()
                    }, 1200)
                },
                fail: (err) => {
                    this.isLoading = false
                    this.loadingProgress = 0
                    uni.showToast({
                        title: '拍照失败，请重试',
                        icon: 'none'
                    })
                }
            })
        },
        speak(){
            if(!this.canSpeak){ return }
            
            this.isSpeaking = true
            
            // 触觉反馈
            if (uni.vibrateShort) {
                try { uni.vibrateShort({ type: 'light' }) } catch(e){}
            }
            
            // 模拟语音播报
            const speakText = this.generateSpeakText()
            console.log('播报内容:', speakText)
            
            // 实际应用中这里会调用语音合成API
            uni.showToast({
                title: `正在播报：${speakText.substring(0, 10)}...`,
                icon: 'none',
                duration: 3000
            })
            
            // 模拟播报完成
            setTimeout(() => {
                this.isSpeaking = false
                uni.showToast({
                    title: '播报完成',
                    icon: 'success'
                })
            }, 3000)
        },
        
        generateSpeakText() {
            if (this.structuredData) {
                return `药品信息：用法用量，${this.structuredData.usage}。注意事项，${this.structuredData.caution}。禁忌症，${this.structuredData.contraindication}。`
            }
            return this.content
        },
        
        // 新增方法
        copyResult() {
            uni.setClipboardData({
                data: this.content,
                success: () => {
                    uni.showToast({
                        title: '已复制到剪贴板',
                        icon: 'success'
                    })
                }
            })
        },
        
        shareResult() {
            uni.showActionSheet({
                itemList: ['分享给朋友', '保存到相册', '发送给医生'],
                success: (res) => {
                    const actions = ['分享给朋友', '保存到相册', '发送给医生']
                    uni.showToast({
                        title: `已选择：${actions[res.tapIndex]}`,
                        icon: 'none'
                    })
                }
            })
        },
        
        handleManualInput() {
            if (!this.manual.trim()) {
                uni.showToast({
                    title: '请输入药品名称',
                    icon: 'none'
                })
                return
            }
            
            // 在药品数据库中查找
            const drug = this.drugDatabase.find(d => 
                d.name.includes(this.manual) || this.manual.includes(d.name)
            )
            
            if (drug) {
                this.content = `药品名称：${drug.name}。用法用量：${drug.usage}。注意事项：${drug.caution}。禁忌症：${drug.contraindication}。`
                this.structuredData = {
                    usage: drug.usage,
                    caution: drug.caution,
                    contraindication: drug.contraindication
                }
                this.pushHistory({
                    name: drug.name,
                    content: this.content,
                    time: Date.now(),
                    structured: this.structuredData
                })
                this.manual = ''
                this.speak()
            } else {
                uni.showToast({
                    title: '未找到该药品信息',
                    icon: 'none'
                })
            }
        },
        
        clearManual() {
            this.manual = ''
        },
        
        formatTime(timestamp) {
            const date = new Date(timestamp)
            const now = new Date()
            const diff = now - date
            
            if (diff < 60000) { // 1分钟内
                return '刚刚'
            } else if (diff < 3600000) { // 1小时内
                return Math.floor(diff / 60000) + '分钟前'
            } else if (diff < 86400000) { // 1天内
                return Math.floor(diff / 3600000) + '小时前'
            } else {
                return date.toLocaleDateString()
            }
        },
        
        clearHistory() {
            uni.showModal({
                title: '清空历史记录',
                content: '确定要清空所有历史记录吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.history = []
                        uni.setStorageSync('ocr_history', [])
                        uni.showToast({
                            title: '已清空历史记录',
                            icon: 'success'
                        })
                    }
                }
            })
        },
        openSpeakSettings(){
            uni.showActionSheet({
                itemList:['语速：慢','语速：中','语速：快','音色：女声','音色：男声'],
                success:(res)=>{
                    const i=res.tapIndex
                    if(i===0) this.voiceRate=0.8
                    if(i===1) this.voiceRate=1
                    if(i===2) this.voiceRate=1.2
                    if(i===3) this.voiceType='female'
                    if(i===4) this.voiceType='male'
                    uni.showToast({ title:'已更新播报设置', icon:'none' })
                }
            })
        },
        openManual(){ uni.showToast({ title:'药品说明书（示例）', icon:'none' }) },
        openCaution(){ uni.showToast({ title:'用药注意事项（示例）', icon:'none' }) },
        addReminder(){ uni.showToast({ title:'已添加用药提醒（示例）', icon:'none' }) },
        pushHistory(item){
            const list=[item, ...this.history].slice(0,20)
            this.history=list
            try{ uni.setStorageSync('ocr_history', list) }catch(e){}
        },
        loadHistory(){
            try{
                const list=uni.getStorageSync('ocr_history')
                if(Array.isArray(list)) this.history=list
            }catch(e){}
        },
        applyHistory(h){ this.content=h.content }
    }
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: $elderly-bg-secondary;
  padding: $elderly-spacing-base;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: $elderly-spacing-lg;
  padding: $elderly-spacing-base;
}

.page-title {
  color: $elderly-text-primary;
  margin-bottom: $elderly-spacing-xs;
}

.page-subtitle {
  color: $elderly-text-secondary;
}

/* 拍照识别区域 */
.capture-section {
  position: relative;
  margin-bottom: $elderly-spacing-lg;
}

.capture {
  min-height: 300rpx;
  background: linear-gradient(135deg, $theme-blue, $theme-orange);
  border-radius: $elderly-radius-lg;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  padding: $elderly-spacing-xl;
  box-shadow: $elderly-shadow-lg;
  border: 4rpx solid white;
}

.capture.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.capture-icon {
  margin-bottom: $elderly-spacing-base;
}

.camera-emoji {
  font-size: 120rpx;
}

.capture-text {
  font-weight: 700;
  margin-bottom: $elderly-spacing-xs;
  text-align: center;
}

.capture-hint {
  opacity: 0.9;
  text-align: center;
}

/* 加载状态 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  border-radius: $elderly-radius-lg;
}

.loading-spinner {
  margin-bottom: $elderly-spacing-base;
}

.spinner-icon {
  font-size: 80rpx;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-bottom: $elderly-spacing-base;
  text-align: center;
}

.loading-progress {
  width: 200rpx;
  height: 8rpx;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, $theme-orange, $theme-blue);
  transition: width 0.3s ease;
}

/* 识别结果 */
.result-section {
  background: $elderly-bg-primary;
  border-radius: $elderly-radius-lg;
  padding: $elderly-spacing-lg;
  margin-bottom: $elderly-spacing-lg;
  box-shadow: $elderly-shadow-base;
  border: 2rpx solid $elderly-border;
}

.result-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $elderly-spacing-base;
}

.result-title {
  color: $elderly-text-primary;
}

.result-actions {
  display: flex;
  gap: $elderly-spacing-sm;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: $elderly-spacing-xs;
  min-width: $elderly-touch-sm;
  min-height: $elderly-touch-sm;
  background: $elderly-bg-secondary;
  border-radius: $elderly-radius-base;
  border: 2rpx solid $elderly-border;
}

.action-icon {
  font-size: $elderly-font-lg;
  margin-bottom: 4rpx;
}

.action-label {
  color: $elderly-text-secondary;
  font-size: $elderly-font-xs;
}

.result-content {
  margin-bottom: $elderly-spacing-base;
}

.result-text {
  color: $elderly-text-primary;
  line-height: 1.6;
}

/* 结构化信息 */
.structured-info {
  background: $elderly-bg-secondary;
  border-radius: $elderly-radius-base;
  padding: $elderly-spacing-base;
  border: 2rpx solid $elderly-border;
}

.info-item {
  display: flex;
  margin-bottom: $elderly-spacing-sm;
  align-items: flex-start;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  color: $theme-orange;
  font-weight: 600;
  min-width: 120rpx;
  margin-right: $elderly-spacing-sm;
}

.info-value {
  color: $elderly-text-primary;
  flex: 1;
}

/* 语音控制 */
.voice-controls {
  display: flex;
  align-items: center;
  gap: $elderly-spacing-base;
  margin-bottom: $elderly-spacing-lg;
  justify-content: center;
}

.voice-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: $elderly-spacing-base;
  min-width: $elderly-touch-lg;
  min-height: $elderly-touch-lg;
  background: linear-gradient(135deg, $theme-orange, $theme-yellow);
  border-radius: $elderly-radius-lg;
  color: #fff;
  box-shadow: $elderly-shadow-base;
}

.voice-btn.active {
  background: linear-gradient(135deg, $theme-blue, $theme-orange);
  animation: pulse 1.5s ease-in-out infinite;
}

.voice-icon {
  font-size: $elderly-font-xl;
  margin-bottom: 4rpx;
}

.voice-label {
  font-size: $elderly-font-sm;
  text-align: center;
}

.voice-settings {
  display: flex;
  align-items: center;
  justify-content: center;
  width: $elderly-touch-lg;
  height: $elderly-touch-lg;
  background: $elderly-bg-primary;
  border-radius: 50%;
  border: 2rpx solid $elderly-border;
}

.settings-icon {
  font-size: $elderly-font-lg;
  color: $elderly-text-secondary;
}

/* 手动输入 */
.manual-input {
  background: $elderly-bg-primary;
  border-radius: $elderly-radius-lg;
  padding: $elderly-spacing-lg;
  margin-bottom: $elderly-spacing-lg;
  box-shadow: $elderly-shadow-base;
  border: 2rpx solid $elderly-border;
}

.input-title {
  color: $elderly-text-primary;
  margin-bottom: $elderly-spacing-sm;
  font-weight: 600;
}

.manual-input-field {
  width: 100%;
  min-height: $elderly-touch-lg;
  background: $elderly-bg-secondary;
  border-radius: $elderly-radius-base;
  padding: 0 $elderly-spacing-base;
  border: 2rpx solid $elderly-border;
  margin-bottom: $elderly-spacing-sm;
}

.manual-input-field:focus {
  border-color: $theme-blue;
}

.input-actions {
  display: flex;
  gap: $elderly-spacing-sm;
}

.input-btn {
  flex: 1;
  min-height: $elderly-touch-lg;
  background: linear-gradient(135deg, $theme-blue, $theme-orange);
  color: #fff;
  border: none;
  border-radius: $elderly-radius-base;
  font-size: $elderly-font-base;
  font-weight: 600;
}

/* 功能操作 */
.function-actions {
  display: flex;
  gap: $elderly-spacing-sm;
  margin-bottom: $elderly-spacing-lg;
}

.func-btn {
  flex: 1;
  min-height: $elderly-touch-lg;
  background: $elderly-bg-primary;
  border-radius: $elderly-radius-lg;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: $elderly-shadow-base;
  border: 2rpx solid $elderly-border;
  padding: $elderly-spacing-sm;
}

.func-icon {
  font-size: $elderly-font-lg;
  margin-bottom: 4rpx;
}

.func-label {
  color: $elderly-text-primary;
  font-size: $elderly-font-sm;
  text-align: center;
}

/* 历史记录 */
.history-section {
  background: $elderly-bg-primary;
  border-radius: $elderly-radius-lg;
  padding: $elderly-spacing-lg;
  box-shadow: $elderly-shadow-base;
  border: 2rpx solid $elderly-border;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: $elderly-spacing-base;
}

.history-title {
  color: $elderly-text-primary;
}

.history-clear {
  display: flex;
  align-items: center;
  justify-content: center;
  width: $elderly-touch-sm;
  height: $elderly-touch-sm;
  background: $elderly-bg-secondary;
  border-radius: 50%;
  border: 2rpx solid $elderly-border;
}

.clear-icon {
  font-size: $elderly-font-lg;
  color: $elderly-text-secondary;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: $elderly-spacing-sm;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: $elderly-spacing-base;
  background: $elderly-bg-secondary;
  border-radius: $elderly-radius-base;
  border: 2rpx solid $elderly-border;
}

.history-content {
  flex: 1;
}

.history-name {
  color: $elderly-text-primary;
  font-weight: 600;
  margin-bottom: 4rpx;
}

.history-time {
  color: $elderly-text-secondary;
  font-size: $elderly-font-xs;
}

.history-arrow {
  color: $elderly-text-secondary;
  font-size: $elderly-font-lg;
  margin-left: $elderly-spacing-sm;
}

/* 动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
</style>

